package com.example.xymarket.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xymarket.adapter.MerchantAdapter;
import com.example.xymarket.adapter.MyPagerAdapter;
import com.example.xymarket.myView.StatusBar;
import com.example.xymarket.myView.myListView;
import com.example.xymarket.R;
import com.example.xymarket.httpUtil.MerchantService;
import com.example.xymarket.po.Category;
import com.example.xymarket.httpUtil.AsyncImageLoader;
import com.example.xymarket.httpUtil.GoodsService;
import com.example.xymarket.po.Merchant;
import com.example.xymarket.common.MyUrl;
import com.example.xymarket.common.MyHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HomeActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private LinearLayout ll_point;
    private TextView tv_name;

    private ArrayList<ImageView> pictures;//图片集合

    private final int[] imageId = {R.mipmap.juzi, R.mipmap.youzi,R.mipmap.huolongguo};
    private final String[] imageName={"每天一个橙子，营养健康","柚惑你的胃","越南火龙果"};
    private final int[] goodsId={2,10,12};

    public class Ad
    {
        public ImageView imageView;
        public Integer id;
        public String title;
        public Ad(ImageView imageView,Integer id,String title)
        {
            this.id=id;
            this.imageView=imageView;
            this.title=title;
        }

    }
    private List<Ad> adList=new ArrayList<>();
    /**
     * 上一次高亮的位置
     */
    private int prePosition=0;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /***防止输入法***/
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_home);
        StatusBar.setStatusBarColor(HomeActivity.this,StatusBar.yellow);
        /*更新ImageButton*/
        for(int i=0;i<8;i++)
        {
            ImageView imageButton=(ImageView) findViewById(buttonId[i]);
            imageViewList.add(imageButton);
        }
        Log.i("HomeActivity", "HomeThread ID:" + Thread.currentThread().getId());
        if(GoodsService.imagesMap.size()==0)
        {
            MyHandler myHandler=new MyHandler(getApplicationContext(),Homehandler);
            GoodsService goodsService=new GoodsService(myHandler);
            goodsService.getAllCategory();
        }
        else
        {
            for(Map.Entry<Integer,Drawable> entry:GoodsService.imagesMap.entrySet())
            {
                ImageView imageView=(ImageView)findViewById(entry.getKey());
                imageView.setImageDrawable(entry.getValue());
            }
        }

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        ll_point = (LinearLayout) findViewById(R.id.ll_point);
        tv_name = (TextView) findViewById(R.id.tv_name);

        pictures = new ArrayList<>();

        for (int i = 0; i < imageId.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(imageId[i]);

            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(8,8);
            Ad ad=new Ad(imageView,goodsId[i],imageName[i]);
            adList.add(ad);
            //将图片添加到集合
            //添加点
            ImageView point =new ImageView(this);
            point.setBackgroundResource(R.drawable.point_selector);

            if(i==0){
                point.setEnabled(true);
            }else{
                point.setEnabled(false);
                params.leftMargin=8;
            }

            point.setLayoutParams(params);
            ll_point.addView(point);

        }
        //设置适配器（PagerAdaptor）-item布局-绑定数据
        viewPager.setAdapter(new MyPagerAdapter(adList,this,Homehandler));

        //设置监听viewPager的改变
        viewPager.addOnPageChangeListener(new MyOnPageChangeListener());


        MyHandler myHandler=new MyHandler(this,Homehandler);
        MerchantService merchantService=new MerchantService(myHandler);
        merchantService.getAllMerchant();
    }


    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        /**
         *当页面滑动的时候回调这个方法
         * @param position 当前页面的位置
         * @param positionOffset 滑动页面的百分比
         * @param positionOffsetPixels  在屏幕上滑动的像素
         */
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            //设置对应文本信息
            tv_name.setText(imageName[position]);

            //把上一个高亮的位置设置为默认--灰色
            ll_point.getChildAt(prePosition).setEnabled(false);
            //当前的设置为高亮--红色
            ll_point.getChildAt(position).setEnabled(true);
            prePosition=position;
        }
        /**
         *当某个页面呗选中了回调
         * @param position 被选中页面的位置
         */
        @Override
        public void onPageSelected(int position) {
//            Intent intent = new Intent(HomeActivity.this, GoodsActivity.class);
//            startActivity(intent);overridePendingTransition(0, 0);

        }


        /**
         * 当页面滑动状态变化的时候回调这个方法
         * 静止-》滑动  滑动-》静止  静止-》拖拽
         * @param state
         */
        @Override
        public void onPageScrollStateChanged(int state) {

        }

    }


    public static int[] buttonId={R.id.imageButton1,R.id.imageButton2,R.id.imageButton3,R.id.imageButton4,
            R.id.imageButton5,R.id.imageButton6,R.id.imageButton7,R.id.imageButton18};

    public static List<ImageView> imageViewList=new ArrayList<>();


    void initListView(List<Merchant> list)
    {
        MerchantAdapter merchantAdapter=new MerchantAdapter(list,this,Homehandler);
        myListView myListView=findViewById(R.id.ll1);
        myListView.setAdapter(merchantAdapter);
    }

    @SuppressLint("HandlerLeak")
    public final Handler Homehandler = new Handler()
    {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1) {
                List<Category> list=(List<Category>)msg.obj;
                AsyncImageLoader asyncImageLoader=new AsyncImageLoader();
                for(int i=0;i<8;i++)
                {
                    asyncImageLoader.loadImage2(MyUrl.ImagesUrl+list.get(i).getImage(),imageViewList.get(i),GoodsService.imagesMap);
                }
            }
            if(msg.what==100)
            {
                Intent intent=new Intent(getApplicationContext(),GoodsActivity.class);
                Integer id=(Integer) msg.obj;
                intent.putExtra("id", id);
                startActivity(intent);
            }
            if(msg.what==10)
            {
                List<Merchant> list=(List<Merchant>)msg.obj;
                initListView(list);
            }

            if(msg.what==101)
            {
                Intent intent=new Intent(getApplicationContext(),MerchantActivity.class);
                startActivity(intent);
            }
        }
    };


    public void  ClickViewPager(View view)
    {
        Intent intent = new Intent(getApplicationContext(), ClassifyActivity.class);
        startActivity(intent);overridePendingTransition(0, 0);
    }

    /**
     * 跳转Activity方法
     * @param view
     */
    public void toClassify(View view)
    {
        Intent intent = new Intent(getApplicationContext(), ClassifyActivity.class);
        startActivity(intent);overridePendingTransition(0, 0);
    }

    public void toShoppingCart(View view)
    {
        Intent intent = new Intent(HomeActivity.this, ShoppingCartActivity.class);
        startActivity(intent);overridePendingTransition(0, 0);
    }

    public void toMine(View view)
    {
        Intent intent = new Intent(HomeActivity.this, MineActivity.class);
        startActivity(intent);overridePendingTransition(0, 0);
    }

    public void toMessage(View view)
    {
        Intent intent = new Intent(HomeActivity.this, MessageActivity.class);
        startActivity(intent);overridePendingTransition(0, 0);
    }

    public void toGoods(View view)
    {
        Intent intent = new Intent(HomeActivity.this, GoodsActivity.class);
        startActivity(intent);overridePendingTransition(0, 0);
    }

    public void toSearch(View view)
    {
        try {
            Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
            startActivity(intent);
            overridePendingTransition(0, 0);
        }
        catch (Exception e)
        {

        }
    }


    /**
     * 再按一次退出程序
     * 用时间来计算两次返回之间的时间
     */
    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}